package com.example.qqlaobing.Umoney.view.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.example.qqlaobing.Umoney.R;
import com.example.qqlaobing.Umoney.been.QuanBeen;
import com.example.qqlaobing.Umoney.been.UserInfoBeen;
import com.example.qqlaobing.Umoney.dialog.Dilog_TestingDate;
import com.example.qqlaobing.Umoney.net.NetRequestBusinessDefine;
import com.example.qqlaobing.Umoney.net.NetRequestRULBuilder;
import com.example.qqlaobing.Umoney.presenter.presenterImpl.HomePresenterImpl;
import com.example.qqlaobing.Umoney.presenter.presenterImpl.LoanMoneyPresenterImpl;
import com.example.qqlaobing.Umoney.presenter.presenterImpl.OrderInfoPresenterImpl;
import com.example.qqlaobing.Umoney.view.activity.CertificationCenterActivity;
import com.example.qqlaobing.Umoney.view.activity.LoanActivity;
import com.example.qqlaobing.Umoney.view.activity.LoanActivity1;
import com.example.qqlaobing.Umoney.view.activity.LoginActivity;
import com.example.qqlaobing.Umoney.view.activity.MainActivity;
import com.example.qqlaobing.Umoney.view.activity.MyWebView;
import com.example.qqlaobing.Umoney.view.activity.RenZhengActivity;
import com.example.qqlaobing.Umoney.view.activity.WebActivity;
import com.example.qqlaobing.Umoney.view.fragment.bean.AppLyLoan;
import com.example.qqlaobing.Umoney.view.fragment.bean.GlideImageLoader;
import com.example.qqlaobing.Umoney.view.fragment.bean.HomeBean;
import com.example.qqlaobing.Umoney.view.myview.LoadingDialog;
import com.example.qqlaobing.Umoney.view.myview.PickerView;
import com.google.gson.Gson;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cc.ibooker.ztextviewlib.AutoVerticalScrollTextView;
import cc.ibooker.ztextviewlib.AutoVerticalScrollTextViewUtil;
import okhttp3.Call;
import okhttp3.Request;

/**
 * 新的首页
 * Created by zhanglizhi on 2018/7/13.
 */

public class HomeFragment1 extends Fragment implements View.OnClickListener {
    @BindView(R.id.tv_auto)
    AutoVerticalScrollTextView tvAuto;
    @BindView(R.id.banner_auto)
    Banner bannerAuto;
    @BindView(R.id.tv_describle)
    TextView tv_describle;
    @BindView(R.id.tv_limitmoney)
    TextView tv_limitmoney;
    @BindView(R.id.bt_tvtv)
    TextView bt_tvtv;
    Unbinder unbinder;
    private View rootView;
    private AutoVerticalScrollTextViewUtil autoVerticalScrollTextViewUtil;
    private List list = new ArrayList();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_home1, container, false);
        unbinder = ButterKnife.bind(this, rootView);
        status=true;
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        unbinder = ButterKnife.bind(this, rootView);
        initView();
        initData();
    }

    LoadingDialog dialog;
    Dilog_TestingDate testingDate;
    private void initView() {
        dialog = new LoadingDialog(getContext(), "玩命加载中...");
        bt_tvtv.setOnClickListener(this);
        if (!NetRequestBusinessDefine.login) {
            startActivity(new Intent(getContext(), LoginActivity.class));
            getActivity().finish();
            if (timer != null) {
                timer.cancel();
            }
            return;
        }
        testingDate=new Dilog_TestingDate(getContext());
        dialog.show();
        postData();
        start();
    }

    private void initData() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_tvtv:
                if (!NetRequestBusinessDefine.login) {
                    MainActivity mainActivity1 = (MainActivity) getActivity();
                    startActivity(new Intent(mainActivity1, LoginActivity.class));
                    getActivity().finish();
                    break;
                }
                if (homeBean == null) {
                    return;
                }
                if (homeBean.getData().getData().getAuthstatus() == 1) {
                    if (homeBean.getData().getData().getLoan() == null || homeBean.getData().getData().getLoan().equals("null")) {//走获取额度
                        postapplyLoan(); //获取额度  postapplyLoan(); //获取额度
                    } else {
                        switch (homeBean.getData().getData().getLoan().getStatus()) {
                            case "0"://审核中
                                Toast.makeText(getContext(), homeBean.getData().getData().getBtn_desc(), Toast.LENGTH_LONG).show();
                                break;
                            case "1":
                                if (homeBean.getData().getData().getLoan().getShenhestatus().equals("1") &&
                                        homeBean.getData().getData().getLoan().getStatus1().equals("0")) {//下一步
                                    Intent intent1 = new Intent(getContext(), LoanActivity1.class);
                                    startActivity(intent1);
                                } else if ((homeBean.getData().getData().getLoan().getShenhestatus().equals("1") &&
                                        homeBean.getData().getData().getLoan().getStatus1().equals("1"))) {//放款中
                                    Toast.makeText(getContext(), homeBean.getData().getData().getBtn_desc(), Toast.LENGTH_LONG).show();
                                } else {//被拒绝===下载页面
                                    String h5_url = homeBean.getData().getData().getLoan().getH5_url();
                                    Intent intent = new Intent();
                                    intent.setClass(getContext(), WebActivity.class);
                                    intent.putExtra("url", h5_url);
                                    startActivity(intent);
                                }
                                break;
                            case "2"://立即还款 h5
                                testingDate.show();
                                testingDate.setOnBackTime(new Dilog_TestingDate.OnBackCenter() {
                                    @Override
                                    public void onHuanKuan() {
                                        String Pay_url = homeBean.getData().getData().getLoan().getPay_url();
                                        Intent intent = new Intent();
                                        intent.setClass(getContext(), MyWebView.class);
                                        intent.putExtra("url", NetRequestBusinessDefine.K_HOST_NAME + Pay_url);
                                        startActivity(intent);
                                    }

                                    @Override
                                    public void onYanqi() {
                                        String Pay_url = homeBean.getData().getData().getLoan().getDelay_pay_url();
                                        Intent intent = new Intent();
                                        intent.setClass(getContext(), MyWebView.class);
                                        intent.putExtra("url", NetRequestBusinessDefine.K_HOST_NAME + Pay_url);
                                        startActivity(intent);
                                    }
                                });

                                break;
                            case "3":

                                break;
                            case "4":

                                break;
                            default:

                                break;
                        }

                    }
                } else {//认证界面
                    Toast.makeText(getActivity(), "请先完善认证资料", Toast.LENGTH_SHORT).show();
//                    MainActivity mainActivity5 = (MainActivity) getActivity();
//                    startActivity(new Intent(mainActivity5, RenZhengActivity.class));
//                    mainActivity5.finish();
                    startActivity(new Intent(getActivity(), CertificationCenterActivity.class));
                }
                break;
        }

    }
    private  boolean status=false;
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    HomeBean homeBean;

    /**
     * 获取首页数据
     */
    public void postData() {
        OkHttpUtils
                .post()
                .url(NetRequestRULBuilder.buildRequestUrl(NetRequestBusinessDefine.K_HOME))
                .addHeader("token", NetRequestBusinessDefine.K_TOKEN)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        dialog.close();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        dialog.close();
                        try {
                            Gson gson = new Gson();
                            homeBean = gson.fromJson(response, HomeBean.class);
                            if (homeBean.getStatus() == 1) {
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    JSONObject jsonObject1 = new JSONObject(jsonObject.getString("data"));
                                    JSONObject jsonObject2 = new JSONObject(jsonObject1.getString("data"));
                                    String amount_limit = jsonObject2.getString("amount_limit");
                                    if (amount_limit != null) {
                                        unbinder = ButterKnife.bind(this, rootView);
                                        tv_limitmoney.setText("￥" + amount_limit);//设置额度
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                bt_tvtv.setText(homeBean.getData().getData().getBtn_desc());
                                tv_describle.setText(homeBean.getData().getData().getLoan_desc());
                                for (int i = 0; i < homeBean.getData().getData().getLatest_loads().size(); i++) {
                                    list.add("尾号" + homeBean.getData().getData().getLatest_loads().get(i).getTelephone() + "用户" + "成功申请" + homeBean.getData().getData().getLatest_loads().get(i).getAmount() + "元");
                                }
                                autoVerticalScrollTextViewUtil = new AutoVerticalScrollTextViewUtil(tvAuto, (ArrayList<CharSequence>) list);
                                // 设置滚动的时间间隔
                                autoVerticalScrollTextViewUtil.setDuration(4000);
                                autoVerticalScrollTextViewUtil.stop();
                                // 开启滚动
                                autoVerticalScrollTextViewUtil.start();
                                if (homeBean.getData().getData().getLoan() != null) {
                                    NetRequestBusinessDefine.oderno = homeBean.getData().getData().getLoan().getId();
                                    NetRequestBusinessDefine.oderid = homeBean.getData().getData().getLoan().getOrderno();
                                }
                                final List<String> images = new ArrayList<>();
                                final List<String> urls = new ArrayList<>();
                                for (int i = 0; i < homeBean.getData().getData().getAds().size(); i++) {
                                    images.add(homeBean.getData().getData().getAds().get(i).getImage());
                                    urls.add(homeBean.getData().getData().getAds().get(i).getUrl());
                                }
                                bannerAuto.setImageLoader(new GlideImageLoader());
                                bannerAuto.setImages(images);
                                bannerAuto.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
                                bannerAuto.isAutoPlay(true);
                                bannerAuto.setDelayTime(5000);
                                bannerAuto.start();
                                bannerAuto.setOnBannerListener(position -> {
                                    if( urls.get(position).equals("")|| urls.get(position)==null){
                                        return;
                                    }
                                    Intent intent = new Intent(getActivity(), WebActivity.class);
                                    intent.putExtra("url", urls.get(position));
                                    startActivity(intent);
                                });
                            } else if (homeBean.getStatus() == 401) {
                                startActivity(new Intent(getActivity(), LoginActivity.class));
                                getActivity().finish();
                            } else {
                                if(status) {
                                    Toast.makeText(getContext(), "网络异常！", Toast.LENGTH_LONG).show();
                                    status=false;
                                }
                            }
                        } catch (Exception e) {
                        }
                    }
                });
    }
    /**
     * 获取额度
     */
    public void postapplyLoan() {
        OkHttpUtils
                .post()
                .url(NetRequestRULBuilder.buildRequestUrl(NetRequestBusinessDefine.K_GET_MONEY))
                .addHeader("token", NetRequestBusinessDefine.K_TOKEN)
                .addParams("days", "7")
                .addParams("amount", "10000")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        dialog.close();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        dialog.close();
                        Gson gson = new Gson();
                        AppLyLoan appLyLoan = gson.fromJson(response, AppLyLoan.class);
                        if (appLyLoan.getStatus() == 1) {
                            postData();//刷新首页显示状态
                            Toast.makeText(getContext(), appLyLoan.getData().getData().getInfo(), Toast.LENGTH_LONG).show();
                        } else if (homeBean.getStatus() == 401) {
                            startActivity(new Intent(getContext(), LoginActivity.class));
                            getActivity().finish();
                        } else {
                            if(status) {
                                Toast.makeText(getContext(), "网络异常！", Toast.LENGTH_LONG).show();
                                status=false;
                            }
                        }
                    }
                });
    }

    // 计时器
    private Timer timer;

    /**
     * @param
     * @return void
     * @throws
     * @Description: 开始计时
     */
    public void start() {
        if (timer == null) {
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    postData();
                    i++;
                }
            }, 0, 5000);
        }
    }

    int i = 0;

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
    }
}
